package com.zzy.demo.common.validate;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zzy.demo.common.exception.ParamException;
import com.zzy.demo.common.utils.FastJsonUtil;


/**
 * 
 * @author guokaige
 *
 */
public class BeanValidator {
	
	private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
	
	public static <T> Map<String,String> validate(T t, Class<?>... groups){
		Validator validator = validatorFactory.getValidator();
		Set<ConstraintViolation<T>> validateResult = validator.validate(t, groups);
		if(validateResult.isEmpty()) {
			return Collections.emptyMap();
		}else {
			LinkedHashMap<String,String> errors= Maps.newLinkedHashMap();
			Iterator<ConstraintViolation<T>> iterator = validateResult.iterator();
			while(iterator.hasNext()) {
				ConstraintViolation<T> violation = iterator.next();
				errors.put(violation.getPropertyPath().toString(), violation.getMessage());
			}
			return errors;
		}
	}
	
	public static <T> Map<String,String> validateList(Collection<?> collection){
		Preconditions.checkNotNull(collection);
		Iterator<?>  iterator = collection.iterator();
		Map<String, String> errors;
		do {
			if(!iterator.hasNext()) {
				return Collections.emptyMap();
			}
			Object object = iterator.next();
			errors = validate(object,new Class[0]);
		}while(errors.isEmpty());
		
		return errors;
	}
	
	public static  Map<String,String> validdateObject(Object first, Object...objects ){
		if(objects !=null && objects.length>0) {
			return validateList(Lists.asList(first, objects));
		}else {
			return validate(first, new Class[0]);
		}
	}
	
	
	public static void check(Object param){
		 Map<String,String> map = BeanValidator.validdateObject(param);
		 if(!map.isEmpty()) {
			 throw new ParamException(FastJsonUtil.fastJsonSerialize(map));
		 }
	}

}
